/**
 * 2020-07-14
 * 登录
 */
'use strict';
const crypto = require('crypto');
const jwt = require('jwt-simple');
const {passSecret,tokenExp} = require('const-data');
const db = uniCloud.database();
exports.main = async (event, context) => {
  let data = {
    appid: "wx3222ed0c3d073b5b",
    secret: "a1e0f3bfc5eef549c1ef968a931bf6b2",
    js_code: event.code,
    grant_type: 'authorization_code'
  }
  
  const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/sns/jscode2session', {
    method: 'GET',
    data,
    dataType: 'json'
  })
  
  const success = res.status === 200 && res.data && res.data.openid
  if (!success) {
    return {
      status: -1,
  	  other:"no",
      msg: '微信登录失败'
    }
  }
  
  const {
    openid,
  } = res.data
  
  let userInfo = {
      openid
    }
  
    let tokenSecret = crypto.randomBytes(16).toString('hex'),
  	  token = jwt.encode(userInfo, tokenSecret)
  
    const userInDB = await db.collection('usermp').where({
      openid
    }).get()
  
    let userUpdateResult
    if (userInDB.data && userInDB.data.length === 0) {
      userUpdateResult = await db.collection('usermp').add({
        ...userInfo,
        tokenSecret,
        exp: Date.now() + tokenExp
      })
    } else {
      userUpdateResult = await db.collection('usermp').doc(userInDB.data[0]._id).set({
        ...userInfo,
        tokenSecret,
        exp: Date.now() + tokenExp
      })
    }
  
    if (userUpdateResult.id || userUpdateResult.affectedDocs === 1) {
  	  // 获取 id
  	  let res = await db.collection('usermp').where({openid}).get();
  	  
  	  if(res.affectedDocs === 1 || res.data.length !== 0){
  		  return {
  		    status: 0,
  		    token,
  		    userID:res.data[0]._id,
  		    msg: '登录成功'
  		  }
  	  } else {
  		 return {
  			status: -1,
  			msg: '微信登录失败'
  		}  
  	  }
     
    }
  
    return {
      status: -1,
      msg: '微信登录失败'
    }
};
